<template>
<div>
  <!-- 面包屑导航区 -->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
    <el-breadcrumb-item>权限列表</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card>
    <!-- 添加角色按钮区 -->
    <el-row>
      <el-button type="primary">添加角色</el-button>
    </el-row>
    <!-- 角色列表 -->
    <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template v-slot="scope">
          <el-row :class="['bdbottom','vcenter',i1==0 ?'dbtop':'']" v-for="(item,i1) in scope.row.children" :key="item.id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag @close="removeRightById(scope.row,item.id)" closable>{{item.authName}}</el-tag><i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <el-row :class="[i2%3===0 ?'':'dbtop','vcenter']" v-for="(item2,i2) in item.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag @close="removeRightById(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag @close="removeRightById(scope.row,item3.id)" closable v-for="(item3) in item2.children" :key="item3.id" type="warning">{{item2.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <!-- 修改按钮-->
          <el-button type="primary" icon="el-icon-edit"></el-button>
          <!-- 删除按钮-->
          <el-button type="danger" icon="el-icon-delete"></el-button>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" @click="showSetRightDialog(scope.row)" icon="el-icon-setting"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>
  </el-card>
  <!-- 分配权限的对话框 -->
  <el-dialog @close="setRightDialogClosed" title="提示" :visible.sync="setRightDialogVisble" width="50%">
    <!-- 树形结构 -->
    <el-tree ref="treeRef" default-expand-all :default-checked-keys="defKeys" show-checkbox node-key="id" :data="rightList" :props="tressProps" ></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisble = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightList:[],
      roleId:'',
      // 默认选中的数组列表
       defKeys:[],
      setRightDialogVisble:false,
      // 属性控件的属性绑定对象
      tressProps:{
        label:'authName',
        children:'children'
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const {
        data: res
      } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.console.error('获取角色列表失败');
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    removeRightById(role, rightId) {
      // 弹框提示用户是否确认删除
      this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {
          data: res
        } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        //  console.log(role.id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        console.log(res)
        this.getRolesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 展示分配权限的方法
    async showSetRightDialog(role) {
      this.roleId= role.id
      // 获取权限的数据
     const {data:res} = await this.$http.get('rights/tree')
     if(res.meta.status!==200)
     return this.$message.error('获取数据失败')
     this.rightList = res.data
    //  console.log(role)

    //  递归获取三级节点

    this.getLeafKeys(role,this.defKeys)
    //  打开弹窗
     this.setRightDialogVisble=true
    },
    // 通过递归去三级节点保存到数组中
    getLeafKeys(node,arr){
      // 如果当前节点不包含children属性
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item,arr)
      });
    },
    setRightDialogClosed(){
      this.rolesList=[]
    },
    async allotRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
    const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
      rids:idStr
    })
    // console.log(res)
    if(res.meta.status!==200)
    return this.$message.error('修改用户权限失败')
    this.$message.success('修改用户权限成功')
    this.setRightDialogVisble=false
     this.getRolesList()
    }
  }

}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.dbtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
